package com.suxin.mqtt.util;

import com.suxin.mqtt.domain.MqMessage;
import org.eclipse.paho.client.mqttv3.MqttClient;
import org.eclipse.paho.client.mqttv3.MqttConnectOptions;
import org.eclipse.paho.client.mqttv3.MqttException;
import org.eclipse.paho.client.mqttv3.MqttMessage;
import org.eclipse.paho.client.mqttv3.persist.MemoryPersistence;

import java.util.UUID;

/**
 * @Classname MqttClientProxy
 * @Description [ TODO ]
 * @Author Tang
 * @Date 2020/12/1 14:44
 * @Created by ASUS
 */
public class MqttClientProxy {

    private String username;

    private String password;

    private String url;

    private MqttClient client;

    public MqttClientProxy(String url,
                           String username, String password) {
        this.url = url;
        this.username = username;
        this.password = password;
        MemoryPersistence persistence = new MemoryPersistence();
        // MQTT 连接选项
        MqttConnectOptions connOpts = new MqttConnectOptions();
//      connOpts.setUserName("emqx_test");
//      connOpts.setPassword("emqx_test_password".toCharArray());
        connOpts.setCleanSession(true);
        try {
            client = new MqttClient(url, UUID.randomUUID().toString(), persistence);
            client.connect(connOpts);
        } catch (MqttException e) {
            e.printStackTrace();
        }

    }

    /**
     * 发布消息
     * @param mqMessage
     */
    public void publish(MqMessage mqMessage) {
        try {
            MqttMessage message = new MqttMessage(mqMessage.getPayLoad().getBytes());
            message.setQos(1);
            client.publish(mqMessage.getTopic(), message);
            System.out.println("Message published success!");
        } catch (MqttException e) {
            e.printStackTrace();
        }
    }

    /**
     * 注册回调
     * @param topic
     * @param consumer
     */
    public void register(String topic, AbstractConsumer consumer) {
        try {
            client.setCallback(consumer);
            client.subscribe(topic);
        } catch (MqttException e) {
            e.printStackTrace();
        }
    }

    /**
     * 断开连接
     */
    public void disconnect() {
        try {
            client.disconnect();
            client.close();
        } catch (MqttException e) {
            e.printStackTrace();
        }
    }

}